package com.qf.filter;

import com.qf.pojo.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @date 2022/3/29
 * @desc
 */
@WebFilter(urlPatterns = {"/*"})
public class PermissionFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        System.out.println("访问某些受保护资源时 ，判断用户是否登录  没有登陆 就跳转到登录页面");

        // 接口 转为 实现类 类型    因为 要调用实现类 特有的方法  getRequestURI()
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;

        String requestURI = req.getRequestURI();




        System.out.println(requestURI);

        if(requestURI.contains("login")||requestURI.contains("createcode")||requestURI.contains("layui")){
            // 登录操作 直接放行
            chain.doFilter(req, resp);
        }else{
            // 其他访问  判断有没有登录
            HttpSession session = req.getSession();

           User user = (User) session.getAttribute("currentUser");

            if(user!=null){
                // 登录过了 放行
                chain.doFilter(req, resp);
            }else{
                //没有登陆 去登录页面
                resp.sendRedirect("/login.jsp");
            }
        }
    }

    @Override
    public void destroy() {

    }
}
